<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <title>测试用例 - AI Worker</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #0e7490 0%, #0891b2 50%, #06b6d4 100%);
            min-height: 100vh;
            padding: 30px 20px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            color: white;
        }

        .header h1 {
            font-size: 2em;
        }

        .btn-back {
            background: rgba(255,255,255,0.2);
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-back:hover {
            background: rgba(255,255,255,0.3);
        }

        .panel {
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }

        .panel-title {
            font-size: 1.4em;
            color: #333;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e9ecef;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }

        .form-group select {
            width: 100%;
            padding: 12px;
            border: 2px solid #dee2e6;
            border-radius: 8px;
            font-size: 1em;
            transition: border-color 0.3s;
        }

        .form-group select:focus {
            outline: none;
            border-color: #0891b2;
            box-shadow: 0 0 0 3px rgba(8, 145, 178, 0.1);
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 1em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-success {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3);
        }

        .btn-primary {
            background: linear-gradient(135deg, #0891b2 0%, #0e7490 100%);
            color: white;
            box-shadow: 0 4px 15px rgba(8, 145, 178, 0.3);
        }

        .btn-warning {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            color: white;
            box-shadow: 0 4px 15px rgba(245, 158, 11, 0.3);
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.3);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .testcase-list {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .testcase-item {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            border-left: 4px solid #0891b2;
        }

        .testcase-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .testcase-title {
            font-size: 1.1em;
            font-weight: 600;
            color: #333;
        }

        .testcase-meta {
            color: #999;
            font-size: 0.9em;
            margin-bottom: 10px;
        }

        .testcase-content {
            color: #666;
            max-height: 150px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: pre-wrap;
        }

        .testcase-actions {
            margin-top: 10px;
            display: flex;
            gap: 8px;
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 0.9em;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }

        .empty-state-icon {
            font-size: 3em;
            margin-bottom: 15px;
        }

        .message {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
        }

        .message.show {
            display: block;
        }

        .message.error {
            background: #f8d7da;
            color: #721c24;
            border-left: 4px solid #dc3545;
        }

        .message.success {
            background: #d4edda;
            color: #155724;
            border-left: 4px solid #28a745;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #999;
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #0891b2;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* AI模型选择样式 */
        .model-buttons {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 12px;
            margin-top: 10px;
        }

        .model-btn {
            padding: 15px 20px;
            border: 2px solid #dee2e6;
            border-radius: 10px;
            background: white;
            cursor: pointer;
            transition: all 0.3s;
            text-align: left;
        }

        .model-btn:hover {
            border-color: #0891b2;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(8, 145, 178, 0.2);
        }

        .model-btn.selected {
            border-color: #0891b2;
            background: linear-gradient(135deg, #0891b2 0%, #0e7490 100%);
            color: white;
        }

        .model-name {
            font-weight: 600;
            margin-bottom: 5px;
            font-size: 1.1em;
        }

        .model-info {
            font-size: 0.85em;
            margin-top: 4px;
            opacity: 0.8;
        }

        .model-badge {
            display: inline-block;
            padding: 3px 8px;
            background: #e9ecef;
            color: #666;
            border-radius: 12px;
            font-size: 0.75em;
            margin-top: 8px;
        }

        .model-btn.selected .model-badge {
            background: rgba(255, 255, 255, 0.3);
            color: white;
        }

        /* 进度条样式 */
        .progress-container {
            margin-top: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #dee2e6;
        }

        .progress-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            font-size: 0.9em;
            color: #495057;
        }

        .progress-bar {
            width: 100%;
            height: 24px;
            background: #e9ecef;
            border-radius: 12px;
            overflow: hidden;
            position: relative;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #0891b2 0%, #0e7490 100%);
            border-radius: 12px;
            transition: width 0.3s ease;
            width: 0%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 0.85em;
            font-weight: 600;
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.6; }
        }

        .progress-fill.animating {
            animation: pulse 1.5s ease-in-out infinite;
        }

        /* 编辑模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            animation: fadeIn 0.3s;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .modal.show {
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background-color: white;
            border-radius: 15px;
            width: 90%;
            max-width: 900px;
            max-height: 90vh;
            display: flex;
            flex-direction: column;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
            animation: slideUp 0.3s;
        }

        @keyframes slideUp {
            from {
                transform: translateY(50px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .modal-header {
            padding: 20px 30px;
            border-bottom: 2px solid #e9ecef;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-title {
            font-size: 1.5em;
            font-weight: 600;
            color: #333;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 1.8em;
            color: #999;
            cursor: pointer;
            padding: 0;
            width: 35px;
            height: 35px;
            border-radius: 50%;
            transition: all 0.3s;
        }

        .modal-close:hover {
            background: #f8f9fa;
            color: #333;
        }

        .modal-body {
            padding: 30px;
            overflow-y: auto;
            flex: 1;
        }

        .modal-footer {
            padding: 20px 30px;
            border-top: 2px solid #e9ecef;
            display: flex;
            gap: 15px;
            justify-content: flex-end;
        }

        .edit-textarea {
            width: 100%;
            min-height: 400px;
            padding: 15px;
            border: 2px solid #dee2e6;
            border-radius: 8px;
            font-family: 'Courier New', monospace;
            font-size: 0.95em;
            line-height: 1.6;
            resize: vertical;
        }

        .edit-textarea:focus {
            outline: none;
            border-color: #0891b2;
            box-shadow: 0 0 0 3px rgba(8, 145, 178, 0.1);
        }

        /* 滚动容器样式 */
        .testcase-list-container {
            max-height: 600px;
            overflow-y: auto;
            padding-right: 10px;
        }

        .testcase-list-container::-webkit-scrollbar {
            width: 8px;
        }

        .testcase-list-container::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }

        .testcase-list-container::-webkit-scrollbar-thumb {
            background: #0891b2;
            border-radius: 10px;
        }

        .testcase-list-container::-webkit-scrollbar-thumb:hover {
            background: #0e7490;
        }

        .testcase-content {
            color: #666;
            max-height: 150px;
            overflow-y: auto;
            text-overflow: ellipsis;
            white-space: pre-wrap;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 6px;
            margin-top: 10px;
        }

        .testcase-content::-webkit-scrollbar {
            width: 6px;
        }

        .testcase-content::-webkit-scrollbar-track {
            background: #e9ecef;
            border-radius: 6px;
        }

        .testcase-content::-webkit-scrollbar-thumb {
            background: #adb5bd;
            border-radius: 6px;
        }

        /* 文档内容样式 */
        .content-container {
            width: 100%;
            max-height: 600px;
            overflow-y: auto;
            border: 2px solid #dee2e6;
            border-radius: 8px;
            background: #f8f9fa;
            margin: 15px 0;
            padding: 20px;
            font-family: 'Courier New', monospace;
            white-space: pre-wrap;
            font-size: 0.9em;
            line-height: 1.6;
            color: #333;
        }
        
        .content-container::-webkit-scrollbar {
            width: 8px;
        }
        
        .content-container::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        
        .content-container::-webkit-scrollbar-thumb {
            background: #0891b2;
            border-radius: 4px;
        }
        
        .content-container::-webkit-scrollbar-thumb:hover {
            background: #0e7490;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📝 测试用例</h1>
            <button class="btn-back" onclick="goBack()">← 返回项目</button>
        </div>

        <!-- 生成配置 -->
        <div class="panel">
            <div class="panel-title">生成新用例</div>
            <div id="messageBox" class="message"></div>
            
            <div class="form-group">
                <label>选择AI模型</label>
                <div class="model-buttons" id="modelButtons">
                    <!-- AI模型按钮将在这里动态生成 -->
                </div>
            </div>

            <button class="btn btn-success" onclick="generateTestCase()" id="generateBtn">
                ✨ 生成测试用例
            </button>
            
            <!-- 进度条 -->
            <div id="progressContainer" class="progress-container" style="display: none;">
                <div class="progress-header">
                    <span id="progressText">准备中...</span>
                    <span id="progressPercent">0%</span>
                </div>
                <div class="progress-bar">
                    <div id="progressFill" class="progress-fill"></div>
                </div>
            </div>
        </div>

        <!-- 用例列表 -->
        <div class="panel">
            <div class="panel-title">用例列表</div>
            <div id="testCasesList">
                <div class="loading">
                    <div class="spinner"></div>
                    <p>加载中...</p>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑模态框 -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title">✏️ 编辑测试用例</h2>
                <button class="modal-close" onclick="closeEditModal()">&times;</button>
            </div>
            <div class="modal-body">
                <textarea id="editTextarea" class="edit-textarea" placeholder="请输入测试用例内容..."></textarea>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="closeEditModal()">取消</button>
                <button class="btn btn-success" onclick="saveTestCase()" id="saveBtn">💾 保存</button>
            </div>
        </div>
    </div>


    <script>
        const projectId = window.location.pathname.split('/')[2];
        let aiModels = [];
        let selectedProvider = null;
        let selectedKeyId = null;
        let currentProject = null;
        let currentEditingTestCaseId = null;

        // 页面加载
        window.onload = function() {
            loadProject();
            loadAIModels();
            loadTestCases();
        };

        // 加载项目信息
        async function loadProject() {
            try {
                const response = await fetch(`/api/project/${projectId}`);
                if (!response.ok) throw new Error('加载项目失败');
                currentProject = await response.json();
            } catch (error) {
                console.error('加载项目失败:', error);
                showMessage('加载项目信息失败: ' + error.message, 'error');
            }
        }

        // 加载AI模型
        async function loadAIModels() {
            try {
                const response = await fetch('/api/models');
                const data = await response.json();
                if (data.success) {
                    aiModels = data.models || [];
                    renderModelButtons();
                }
            } catch (error) {
                console.error('加载AI模型失败:', error);
            }
        }

        // 渲染模型按钮
        function renderModelButtons() {
            const container = document.getElementById('modelButtons');
            
            if (!aiModels || aiModels.length === 0) {
                container.innerHTML = '<p style="color: #999;">暂无可用的AI模型</p>';
                return;
            }
            
            const buttonsHtml = aiModels.map((model, index) => `
                <div class="model-btn" onclick="selectModel('${model.provider}', '${model.key_id || ''}', ${index})" id="model-btn-${index}">
                    <div class="model-name">${getProviderIcon(model.provider)} ${escapeHtml(model.name)}</div>
                    <div class="model-info">${escapeHtml(model.model)}</div>
                    <span class="model-badge">${escapeHtml(model.provider)}</span>
                </div>
            `).join('');
            
            container.innerHTML = buttonsHtml;
            
            // 默认选中第一个
            if (aiModels.length > 0) {
                selectModel(aiModels[0].provider, aiModels[0].key_id || '', 0);
            }
        }

        // 获取提供商图标
        function getProviderIcon(provider) {
            const icons = {
                'doubao': '🤖',
                'deepseek': '🔮',
                'gemini': '<img src="https://www.gstatic.com/lamda/images/gemini_sparkle_4g_512_lt_f94943af3be039176192d.png" style="width: 20px; height: 20px; vertical-align: middle;">'
            };
            return icons[provider] || '🤖';
        }

        // 选择模型
        function selectModel(providerId, keyId, index) {
            // 移除所有选中状态
            document.querySelectorAll('.model-btn').forEach(btn => {
                btn.classList.remove('selected');
            });
            
            // 添加选中状态
            const btn = document.getElementById(`model-btn-${index}`);
            if (btn) {
                btn.classList.add('selected');
            }
            
            selectedProvider = providerId;
            selectedKeyId = keyId;
        }

        // 生成测试用例
        async function generateTestCase() {
            if (!selectedProvider) {
                showMessage('请选择AI模型', 'error');
                return;
            }
            
            // 检查项目是否有文档来源
            if (!currentProject || !currentProject.document_source) {
                showMessage('请提供文档来源，文档来源选择创建项目中的文档', 'error');
                return;
            }
            
            const btn = document.getElementById('generateBtn');
            btn.disabled = true;
            btn.textContent = '生成中...';
            
            // 显示进度条
            showProgress(0, '开始生成测试用例...');
            
            try {
                // 模拟进度更新
                const progressInterval = simulateProgress();
                
                const response = await fetch(`/api/project/${projectId}/generate-testcase`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        ai_provider: selectedProvider,
                        ai_key_id: selectedKeyId || null,
                        document_type: currentProject.document_type,
                        document_source: currentProject.document_source
                    })
                });
                
                clearInterval(progressInterval);
                
                const result = await response.json();
                if (!result.success) throw new Error(result.error || '生成失败');
                
                showProgress(100, '生成完成！');
                showMessage('生成成功！', 'success');
                
                setTimeout(() => {
                    hideProgress();
                    loadTestCases();
                }, 1500);
                
            } catch (error) {
                hideProgress();
                showMessage('生成失败: ' + error.message, 'error');
            } finally {
                btn.disabled = false;
                btn.textContent = '✨ 生成测试用例';
            }
        }

        // 显示进度条
        function showProgress(percent, text) {
            const container = document.getElementById('progressContainer');
            const fill = document.getElementById('progressFill');
            const progressText = document.getElementById('progressText');
            const progressPercent = document.getElementById('progressPercent');
            
            container.style.display = 'block';
            fill.style.width = percent + '%';
            progressText.textContent = text;
            progressPercent.textContent = percent + '%';
            
            if (percent < 100) {
                fill.classList.add('animating');
            } else {
                fill.classList.remove('animating');
            }
        }

        // 隐藏进度条
        function hideProgress() {
            const container = document.getElementById('progressContainer');
            container.style.display = 'none';
        }

        // 模拟进度更新
        function simulateProgress() {
            let progress = 0;
            const stages = [
                { percent: 20, text: '正在解析需求文档...' },
                { percent: 40, text: '正在分析功能模块...' },
                { percent: 60, text: 'AI正在生成测试用例...' },
                { percent: 80, text: '正在优化用例结构...' },
                { percent: 90, text: '即将完成...' }
            ];
            let stageIndex = 0;
            
            const interval = setInterval(() => {
                if (stageIndex < stages.length) {
                    const stage = stages[stageIndex];
                    showProgress(stage.percent, stage.text);
                    stageIndex++;
                }
            }, 3000); // 每3秒更新一次
            
            return interval;
        }

        // 加载测试用例列表
        async function loadTestCases() {
            try {
                const response = await fetch(`/api/project/${projectId}/testcases`);
                if (!response.ok) throw new Error('加载失败');
                
                const testCases = await response.json();
                renderTestCases(testCases);
            } catch (error) {
                document.getElementById('testCasesList').innerHTML = `
                    <div class="empty-state">
                        <div class="empty-state-icon">📝</div>
                        <p>暂无测试用例</p>
                    </div>
                `;
            }
        }

        // 渲染测试用例列表
        function renderTestCases(testCases) {
            const container = document.getElementById('testCasesList');
            
            if (!testCases || testCases.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <div class="empty-state-icon">📝</div>
                        <p>暂无测试用例</p>
                        <p style="margin-top: 10px; font-size: 0.9em;">选择AI模型后点击"生成测试用例"开始</p>
                    </div>
                `;
                return;
            }
            
            // 按生成时间倒序排序
            testCases.sort((a, b) => new Date(b.generated_at) - new Date(a.generated_at));
            
            const html = testCases.map(tc => `
                <div class="testcase-item">
                    <div class="testcase-header">
                        <div class="testcase-title">#${tc.id} - ${escapeHtml(tc.title || '测试用例')}</div>
                    </div>
                    <div class="testcase-meta">
                        <strong>用例ID:</strong> ${tc.id} | 
                        <strong>生成时间:</strong> ${new Date(tc.created_at || tc.generated_at).toLocaleString('zh-CN')}
                    </div>
                    <div class="content-container">${escapeHtml(tc.content || '暂无内容')}</div>
                    <div class="testcase-actions">
                        <button class="btn btn-primary btn-sm" onclick="editTestCase(${tc.id})">
                            ✏️ 编辑
                        </button>
                        <button class="btn btn-success btn-sm" onclick="exportTestCase(${tc.id})">
                            💾 导出
                        </button>
                    </div>
                </div>
            `).join('');
            
            container.innerHTML = `<div class="testcase-list-container"><div class="testcase-list">${html}</div></div>`;
        }

        // 编辑测试用例
        async function editTestCase(id) {
            try {
                // 获取测试用例详情
                const response = await fetch(`/api/testcase/${id}`);
                const data = await response.json();
                
                if (!data.success) {
                    throw new Error(data.error || '加载失败');
                }
                
                // 设置当前编辑的用例ID和内容
                currentEditingTestCaseId = id;
                document.getElementById('editTextarea').value = data.testcase.content || '';
                
                // 显示模态框
                document.getElementById('editModal').classList.add('show');
            } catch (error) {
                showMessage('加载测试用例失败: ' + error.message, 'error');
            }
        }

        // 关闭编辑模态框
        function closeEditModal() {
            document.getElementById('editModal').classList.remove('show');
            currentEditingTestCaseId = null;
            document.getElementById('editTextarea').value = '';
        }

        // 保存测试用例
        async function saveTestCase() {
            if (!currentEditingTestCaseId) return;
            
            const content = document.getElementById('editTextarea').value.trim();
            if (!content) {
                showMessage('用例内容不能为空', 'error');
                return;
            }
            
            const saveBtn = document.getElementById('saveBtn');
            const originalText = saveBtn.textContent;
            saveBtn.disabled = true;
            saveBtn.textContent = '保存中...';
            
            try {
                const response = await fetch(`/api/testcase/${currentEditingTestCaseId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ content: content })
                });
                
                const result = await response.json();
                
                if (!result.success) {
                    throw new Error(result.error || '保存失败');
                }
                
                showMessage('保存成功！', 'success');
                closeEditModal();
                
                // 重新加载测试用例列表
                loadTestCases();
            } catch (error) {
                showMessage('保存失败: ' + error.message, 'error');
            } finally {
                saveBtn.disabled = false;
                saveBtn.textContent = originalText;
            }
        }

        // 导出测试用例
        function exportTestCase(id) {
            window.location.href = `/api/testcase/${id}/download`;
        }

        // 点击模态框背景关闭
        document.getElementById('editModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeEditModal();
            }
        });

        // 返回
        function goBack() {
            window.location.href = `/project/${projectId}`;
        }

        // 显示消息
        function showMessage(message, type) {
            const box = document.getElementById('messageBox');
            box.textContent = message;
            box.className = `message ${type} show`;
            
            setTimeout(() => {
                box.classList.remove('show');
            }, type === 'success' ? 3000 : 5000);
        }

        // 辅助函数
        function escapeHtml(text) {
            if (!text) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    </script>
</body>
</html>

